﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;

namespace DZParallelLib.Test
{
    static class UtilsForTest
    {
        /// <summary>
        /// Render as a file for testing.
        /// </summary>
        /// <param name="image"></param>
        public static string AsImageFile(this Bitmap image, string fname = "test.png")
        {
            var f = new FileInfo(fname);
            image.Save(f.FullName);
            return f.FullName;
        }

        /// <summary>
        /// Returns an object of some sort as a string.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string AsString<T>(this T source)
        {
            return source.ToString();
        }

        /// <summary>
        /// Returns a list of some object as a string.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static string AsString<T>(this IEnumerable<T> source)
        {
            var bld = new StringBuilder();
            int index = 0;
            foreach (var item in source)
            {
                index++;
                bld.AppendLine(string.Format("{0}. {1}", index, item.AsString()));
            }
            return bld.ToString().Trim();
        }

        public static void SetupTest()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();

            var c = new RenderDZCollectionFromImages();
            c.DeleteImageDB(new DirectoryInfo(@"."));

            var d = new DirectoryInfo(@".\dzout");
            if (d.Exists)
                d.Delete(true);

            // Find any rendered info files left behind and get rid of them as they
            // represent shared state.

            foreach (var f in Directory.GetFiles(".", "*.rendered_info", SearchOption.AllDirectories))
            {
                File.Delete(f);
            }
        }

        public static void FinishTest()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
    }
}
